package com.hos.db.manager;

import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.hos.db.create.ill.IllsTable;
import com.hos.db.create.user.UserDocTable;
import com.hos.db.entity.UserDocEntity;
import com.hos.db.entity.doc.UserDocLoginEntity;
import com.hos.net.req.doc.DocRegisterReq;
import com.hos.net.req.doc.DocUpdateReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;
import com.hos.utile.Md5Utile;
import com.hos.utile.StringUtile;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DocsManager {

    private static DocsManager userPatsManager;

    public static DocsManager getInstance() {
        if (userPatsManager == null) {
            userPatsManager = new DocsManager();
        }
        return userPatsManager;
    }

    /**
     * @param jdbcTemplate
     * @param req          用户注册参数
     * @return 注册结果
     */
    public String docRegister(JdbcTemplate jdbcTemplate, DocRegisterReq req) {
        boolean isExit = isRegister(jdbcTemplate, req.account);
        if (isExit) {
            return new MsgHint("该账号已存在").toJson();
        }
        String response = new MsgHint("注册失败").toJson();
        String docId = Md5Utile.encode(req.account);
        String sql = "INSERT INTO " + UserDocTable.tableName
                + "("
                + UserDocTable.tableDocId + ","
                + UserDocTable.tableDocName + ","
                + UserDocTable.tableDocAccount + ","
                + UserDocTable.tableDocPwd + ","
                + UserDocTable.tableDocPhone + ","
                + UserDocTable.tableDocPortrait + ","
                + UserDocTable.tableDocHosName + ","
                + UserDocTable.tableDocDeptName + ","
                + UserDocTable.tableDocWorkYear + ","
                + UserDocTable.tableDocRegisterTime
                + ")"
                + " VALUES (?,?, ?, ?,?, ?,?,?, ?, ?)";
        try {
            //String registerTime =new Date();// DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HM);
            int status = jdbcTemplate.update(sql,
                    new Object[]{docId, req.name, req.account, Md5Utile.encode(req.pwd),
                            req.account, req.docHead, req.hosName, req.deptName, req.workYear,
                            new Date()});
            if (status > 0) {
                UserDocEntity user = new UserDocEntity();
                user.setDocAccount(req.account);
                user.setDocName(req.name);
                response = user.toJson("注册成功");
            }
        } catch (Exception e) {
            DLog.e("注册成功：" + e.getMessage());
        }
        return response;
    }

    /**
     * @param jdbcTemplate jdbc
     * @param account   查询账号
     * @return true 账号存在
     */
    /**
     * @param jdbcTemplate jdbc
     * @param patAccount   查询账号
     * @return true 账号存在
     */
    public boolean isRegister(JdbcTemplate jdbcTemplate, String patAccount) {
        String sql = "SELECT * FROM " + UserDocTable.tableName + " WHERE "
                + UserDocTable.tableDocAccount + " = " + patAccount;
        List<UserDocEntity> users = docQuery(jdbcTemplate, sql);
        return users != null && users.size() > 0;
    }

    /**
     * 按手机号码登录
     *
     * @param jdbcTemplate jdbc
     * @param docPhone     登录账户
     * @return
     */
    public String userLoginReq(JdbcTemplate jdbcTemplate, String docPhone, String docPwd, String pushId) {
        docPwd = MD5Util.getMD5Format(docPwd);
        String sql = "SELECT * FROM " + UserDocTable.tableName + " WHERE "
                + UserDocTable.tableDocPhone + " = " + docPhone + " and "
                + UserDocTable.tableDocPwd + " = " + "'" + docPwd + "'";
        DLog.e(sql);
        List<UserDocLoginEntity> users = userQueryLogin(jdbcTemplate, sql);
        if (users == null || users.size() == 0) {
            return new MsgHint("账号或者密码错误").toJson();
        }
        String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
        String token = MD5Util.getMD5Format(docPhone + loginTime);
        UserDocLoginEntity user = users.get(0);
        user.setDocToken(token);
        createToken(jdbcTemplate, docPhone, token, loginTime, pushId);
        //
        BaseResponse<UserDocLoginEntity> baseResponse = new BaseResponse();
        baseResponse.obj = user;
        baseResponse.token = token;
        return baseResponse.toJson("登录成功");
    }


    /**
     * 获取医生
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     * @param hasNextPage  判断是否有下一页
     */
    public List<UserDocEntity> getDocs(JdbcTemplate jdbcTemplate, int pageNo, int pageSize,
                                       boolean hasNextPage) {
        //SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT N][ OFFSET M]
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String sql = "SELECT * FROM " + UserDocTable.tableName
                + " ORDER BY " + UserDocTable.tableDocRegisterTime
                + " DESC "
                //+ "," + UserDocTable.tableId
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        DLog.e("sql:" + sql);
        List<UserDocEntity> user = docQuery(jdbcTemplate, sql);
        if (user == null) {
            user = new ArrayList();
        }
        return user;
    }

    //isPhone true 包含手机号
    public List<UserDocEntity> getDocs(JdbcTemplate jdbcTemplate, String key, boolean isPhone, int pageNo, int pageSize,
                                       boolean hasNextPage) {
        //SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT N][ OFFSET M]
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String where = "";
        if (!StringUtile.isEmpty(key)) {
            where = " WHERE " + UserDocTable.tableDocName + " LIKE '%" + key + "%' ";
        }
        if (isPhone && !StringUtile.isEmpty(key)) {
            where += " OR " + UserDocTable.tableDocPhone + " LIKE '%" + key + "%' ";
        }
        String sql = "SELECT * FROM " + UserDocTable.tableName
                + where
                + " ORDER BY " + UserDocTable.tableDocRegisterTime
                + " DESC "
                //+ "," + UserDocTable.tableId
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        DLog.e("sql:" + sql);
        List<UserDocEntity> user = docQuery(jdbcTemplate, sql);
        if (user == null) {
            user = new ArrayList();
        }
        return user;
    }

    public int getDocs(JdbcTemplate jdbcTemplate, String key) {
        if (StringUtile.isEmpty(key)) {
            return getDocs(jdbcTemplate);
        }
        //select count(*) from user_docs
        String sql = "SELECT count(*) FROM " + UserDocTable.tableName
                + " WHERE " + UserDocTable.tableDocPhone + " LIKE '%" + key + "%' "
                + " OR " + UserDocTable.tableDocName + " LIKE '%" + key + "%' ";
        int count = jdbcTemplate.queryForInt(sql);
        return count;
    }

    public int getDocs(JdbcTemplate jdbcTemplate) {
        //select count(*) from user_docs
        String sql = "SELECT count(*) FROM " + UserDocTable.tableName;
        int count = jdbcTemplate.queryForInt(sql);
        return count;
    }

    //重置密码
    public String updateRestPwdReq(JdbcTemplate jdbcTemplate, String phone, String pwd) {
        String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
        String sql = "UPDATE " + UserDocTable.tableName
                + " SET "
                + UserDocTable.tableDocPwd + " = '" + Md5Utile.encode(pwd) + "',"
                + UserDocTable.tableDocLoninTime + " = '" + loginTime + "'"
                + " WHERE "
                + UserDocTable.tableDocPhone + " = " + phone;
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "修改成功").toJson();
        }
        return new MsgHint("修改失败").toJson();
    }

    //修改医生信息
    public String updateUserReq(JdbcTemplate jdbcTemplate, DocUpdateReq doc) {
        String update = "";
        String name = doc.docName;
        if (!StringUtile.isEmpty(name)) {
            update += " , " + UserDocTable.tableDocName + " = '" + name + "'";
        }
        String docHosName = doc.docHosName;
        if (!StringUtile.isEmpty(docHosName)) {
            update += " , " + UserDocTable.tableDocHosName + " = '" + docHosName + "'";
        }
        String docHosId = doc.docHosId;
        if (!StringUtile.isEmpty(docHosId)) {
            update += " , " + UserDocTable.tableDocHosId + " = '" + docHosId + "'";
        }
        String docDeptName = doc.docDeptName;
        if (!StringUtile.isEmpty(docDeptName)) {
            update += " , " + UserDocTable.tableDocDeptName + " = '" + docDeptName + "'";
        }
        String docDeptId = doc.docDeptId;
        if (!StringUtile.isEmpty(docDeptId)) {
            update += " , " + UserDocTable.tableDocDeptId + " = '" + docDeptId + "'";
        }
        String docTitle = doc.docTitle;
        if (!StringUtile.isEmpty(docTitle)) {
            update += " , " + UserDocTable.tableDocTitle + " = '" + docTitle + "'";
        }
        String patPhone = doc.docPhone;
        if (!StringUtile.isEmpty(patPhone)) {
            update += " , " + UserDocTable.tableDocPhone + " = '" + patPhone + "'";
        }
        String patHaed = doc.docHead;
        if (!StringUtile.isEmpty(patHaed)) {
            update += " , " + UserDocTable.tableDocPortrait + " = '" + patHaed + "'";
        }
        Integer patState = doc.docState;
        if (patState != null && (patState == 1 || patState == 2)) {
            update += " , " + UserDocTable.tableDocState + " = '" + patState + "'";
        }
        Integer docPower = doc.docPower;
        if (docPower != null && docPower >= 0) {
            update += " , " + UserDocTable.tableDocPower + " = '" + docPower + "'";
        }
        String docWorkYear = doc.docWorkYear;
        if (!StringUtile.isEmpty(docWorkYear)) {
            update += " , " + UserDocTable.tableDocWorkYear + " = '" + docWorkYear + "'";
        }
        String docJs = doc.docJs;
        if (!StringUtile.isEmpty(docJs)) {
            update += " , " + UserDocTable.tableDocJS + " = '" + docJs + "'";
        }
        String docSc = doc.docSc;
        if (!StringUtile.isEmpty(docSc)) {
            update += " , " + UserDocTable.tableDocSC + " = '" + docSc + "'";
        }
        if (update.equals("")) {
            return new MsgHint("请设置要修改的参数").toJson();
        }
        update = update.replaceFirst(" , ", "");
        //UPDATE cs_user SET gender = '男' WHERE id = 4
        String sql = "UPDATE " + UserDocTable.tableName
                + " SET "
                + update
                + " WHERE "
                + UserDocTable.tableDocId + " = '" + doc.docId + "'";
        DLog.e(sql);
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            IllsTable. onUpdateDoc(jdbcTemplate,doc.docId,doc.docName);
            return new MsgHint("0", "修改成功").toJson();
        }
        return new MsgHint("修改失败").toJson();
    }

    //更新推送id
    public String updatePushId(JdbcTemplate jdbcTemplate, String docId, String pushId) {
        String sql = "UPDATE " + UserDocTable.tableName
                + " SET "
                + UserDocTable.tableDocPushId + " = '" + pushId + "'"
                + " WHERE "
                + UserDocTable.tableDocId + " = '" + docId + "'";
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "更新失败").toJson();
        }
        return new MsgHint("更新成功").toJson();
    }

    //获取推送id
    public String getPushId(JdbcTemplate jdbcTemplate, String docId) {
        String pushId = "";
        String sql = "SELECT * FROM " + UserDocTable.tableName + " WHERE "
                + UserDocTable.tableDocId + " = '" + docId + "'";
        List<UserDocEntity> users = docQuery(jdbcTemplate, sql);
        if (users != null && users.size() > 0) {
            pushId = users.get(0).getDocPushid();
        }
        return pushId;
    }

    /**
     * 按手机号获取用户
     *
     * @param jdbcTemplate
     * @param phone
     * @return
     */
    public UserDocEntity getUserForPhone(JdbcTemplate jdbcTemplate, String phone) {
        UserDocEntity user = null;
        String sql = "SELECT * FROM " + UserDocTable.tableName + " WHERE "
                + UserDocTable.tableDocPhone + " = " + phone;
        List<UserDocEntity> users = docQuery(jdbcTemplate, sql);
        if (users != null && users.size() > 0) {
            user = users.get(0);
        }
        return user;
    }

    //查询医生
    private List<UserDocLoginEntity> userQueryLogin(JdbcTemplate jdbcTemplate, String sql) {
        List<UserDocLoginEntity> users = null;
        try {
            users = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(UserDocLoginEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return users;
    }

    //查询医生
    private List<UserDocEntity> docQuery(JdbcTemplate jdbcTemplate, String sql) {
        List<UserDocEntity> users = null;
        try {
            users = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(UserDocEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return users;
    }

    //创建token
    public void createToken(JdbcTemplate jdbcTemplate, String account, String token
            , String time, String pushId) {
        String pushUpdate = "";
        if (!StringUtile.isEmpty(pushId)) {
            pushUpdate = " , " + UserDocTable.tableDocPushId + " = '" + pushId + "'";
        }
        String sql = "update  " + UserDocTable.tableName
                + " set "
                + UserDocTable.tableDocToken + " = '" + token + "'"
                + " , "
                + UserDocTable.tableDocLoninTime + " = '" + time + "'"
                + pushUpdate
                + " WHERE "
                + UserDocTable.tableDocAccount + " = " + account;
        jdbcTemplate.update(sql);
    }

    //校验token
    public UserDocEntity verifyTokenUser(JdbcTemplate jdbcTemplate, String token) {
        UserDocEntity user = null;
        if (token == null || token == "") {
            return user;
        }
        String sql = "SELECT * FROM " + UserDocTable.tableName + " WHERE "
                + UserDocTable.tableDocToken + " = '" + token + "'";
        List<UserDocEntity> users = docQuery(jdbcTemplate, sql);

        if (users != null && users.size() > 0) {
            user = users.get(0);
        }
        if (users != null) {
            updateToken(jdbcTemplate, token);
        }
        return user;
    }

    //更新token
    private void updateToken(JdbcTemplate jdbcTemplate, String token) {
        String loginTime = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
        String sql = "update  " + UserDocTable.tableName
                + " set "
                + UserDocTable.tableDocLoninTime + " = '" + loginTime
                + "' WHERE "
                + UserDocTable.tableDocToken + " = '" + token + "'";
        jdbcTemplate.update(sql);
    }
}
